package com.atguigu.springcloud.config;

import com.alibaba.fastjson.JSON;
import com.atguigu.springcloud.dto.BurnCancelTaskDto;
import com.atguigu.springcloud.dto.BurnTaskInfoDto;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;


/**
 * @author xiaolong
 * @version 1.0
 * @description: rabbitmq工具类
 * @date 2021/10/15 17:11
 */
@Slf4j
@ConditionalOnProperty(value = "burn.enable", havingValue = "true")
public class RabbitmqUtil {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private BurnConfig burnConfig;


    /**
     * @param
     * @return
     * @description: 发送消息
     */
    public void send(String exchange, String routeKey, Object obj, Integer correlationDataId) {
        byte[] writeValueAsBytes = null;
        try {
            //将对象转为字节数组
            writeValueAsBytes = objectMapper.writeValueAsBytes(obj);
            ////主要是将消息存储在body中的，将消息的deLiveryMode设置为持久与永久的
            Message message = MessageBuilder.withBody(writeValueAsBytes).setDeliveryMode(MessageDeliveryMode.PERSISTENT).build();
            message.getMessageProperties().setContentType(MessageProperties.CONTENT_TYPE_JSON);
            //发送邮件添加唯一标识CorrelationData
            CorrelationData correlationData = new CorrelationData();
            correlationData.setId(String.valueOf(correlationDataId));
            rabbitTemplate.convertAndSend(exchange, routeKey, message, correlationData);
        } catch (JsonProcessingException e) {
            log.error("发送消息失败", e);
            throw new RuntimeException("发送消息失败，请检查rabbitmq服务");
        }
    }


    /**
     * @param
     * @return
     * @description: 发送任务
     */
    public void sendTask(BurnTaskInfoDto burnTaskInfoDto) {
        log.info("发送任务信息-{}", JSON.toJSONString(burnTaskInfoDto));
        send(burnConfig.burnDownloadExchange, burnConfig.taskStatusRoutingKey, burnTaskInfoDto, burnTaskInfoDto.getTaskId());
    }


    /**
     * @param
     * @return
     * @description: 取消任务
     */
    public void sendCancelTask(BurnCancelTaskDto cancelTaskDto) {
        log.info("发送任务信息-{}", JSON.toJSONString(cancelTaskDto));
        send(burnConfig.burnDownloadExchange, burnConfig.delTaskReqRoutingkey, cancelTaskDto, cancelTaskDto.getTaskId());
    }


}
